package com.example.design.beautiful.unit_test.performance_counter.v2.reporter;

import com.example.design.beautiful.unit_test.performance_counter.aggregator.RequestStat;
import com.example.design.beautiful.unit_test.performance_counter.collector.RequestInfo;
import com.example.design.beautiful.unit_test.performance_counter.reporter.EmailSender;
import com.example.design.beautiful.unit_test.performance_counter.strorage.MetricsStorage;
import com.example.design.beautiful.unit_test.performance_counter.v2.Aggregator;
import com.example.design.beautiful.unit_test.performance_counter.v2.view.StatViewer;

import java.util.*;

public class EmailReporter {
    private static final Long DAY_HOURS_IN_SECONDS = 86400L;

    private MetricsStorage metricsStorage;
    private EmailSender emailSender;
    private List<String> toAddresses = new ArrayList<>();

    private Aggregator aggregator;
    private StatViewer statViewer;


    public EmailReporter(MetricsStorage metricsStorage,
                         Aggregator aggregator, StatViewer statViewer) {
        this.metricsStorage = metricsStorage;
        this.aggregator = aggregator;
        this.statViewer = statViewer;
    }

    public void addToAddress(String address) {
        toAddresses.add(address);
    }

    public void startDailyReport() {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date firstTime = calendar.getTime();
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                long durationInMillis = DAY_HOURS_IN_SECONDS * 1000;
                long endTimeInMillis = System.currentTimeMillis();
                long startTimeInMillis = endTimeInMillis - durationInMillis;
                Map<String, List<RequestInfo>> requestInfos =
                        metricsStorage.getRequestInfos(startTimeInMillis, endTimeInMillis);


                // todo 这块代码可以放到aggregator中
//        Map<String, RequestStat> stats = new HashMap<>();
//        for (Map.Entry<String, List<RequestInfo>> entry : requestInfos.entrySet()) {
//          String apiName = entry.getKey();
//          List<RequestInfo> requestInfosPerApi = entry.getValue();
//          RequestStat requestStat = Aggregator.aggregate(requestInfosPerApi, durationInMillis);
//          stats.put(apiName, requestStat);
//        }
                Map stats = aggregator.aggregate(requestInfos, durationInMillis);

                // todo 将这部分逻辑剥离出来，设计成类
                // TODO: 格式化为html格式，并且发送邮件
//        System.out.println("发邮件");
                statViewer.output(stats, startTimeInMillis, endTimeInMillis);

            }
        }, firstTime, DAY_HOURS_IN_SECONDS * 1000);
    }
}